﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;

public class JoyPad : MonoBehaviour
{
	public Transform joinPadView;
	public Image ball;

    public Vector3 initPos = new Vector3(-768, -342, 0);
    public Action<Vector2> onStop;
    public Action<Vector2> onMove;
    public Action<Vector2> onStay;
    public Action onClick;

    public bool relativeMode;
    public bool stayStopMode;

    public void SetAvoidCheckRange(float avoidCheckRangeMinX, float avoidCheckRangeMaxX, float avoidCheckRangeMinY,
	    float avoidCheckRangeMaxY)
    {
	    this.GetComponentInChildren<JoyPadEvent>().SetAvoidCheckRange(avoidCheckRangeMinX,avoidCheckRangeMaxX,avoidCheckRangeMinY,avoidCheckRangeMaxY);
    }
    
	public void SetPosition (Vector2 position)
	{
		this.joinPadView.localPosition = position;
	}
	public void SetPosition (Vector3 position)
	{
		this.joinPadView.GetComponent<RectTransform>().SetUIPosition(position);
	}
	public void ResetPosition ()
	{
		this.joinPadView.localPosition = initPos;
		this.ball.transform.localPosition = Vector3.zero;
    }

	public void OnPointerDown()
	{
		m_ButtonDownTime = Time.realtimeSinceStartup;
	}
	
    public void OnPointerUp(Vector2 position)
    {
        if (onStop != null)
            onStop(position / JoyPadEvent.limitMax);

        /*if(!this.GetComponentInChildren<JoyPadEvent>().CheckInAvoidRange(position))
        {
	        if (Time.realtimeSinceStartup - m_ButtonDownTime < stayJudgeTime)
	        {
		        onClick?.Invoke();
	        }
        }*/
        
        ResetPosition();
        
        joinPadView.gameObject.SetActive(false);
    }

    private const float stayJudgeTime = 0.15f;

    private float m_ButtonDownTime;
    
    public void OnPointerStay(Vector2 offset)
    {
	    if (Time.realtimeSinceStartup - m_ButtonDownTime >= stayJudgeTime)
	    {
		    onStay?.Invoke(offset / JoyPadEvent.limitMax);
		    
		    if(!joinPadView.gameObject.activeSelf)
			    joinPadView.gameObject.SetActive(true);
	    }
    }

	public void SetBallOffset (Vector2 offset)
	{
		this.ball.transform.localPosition = offset;
		
        if(relativeMode)
	        onMove?.Invoke(offset);
        else
            onMove?.Invoke(offset / JoyPadEvent.limitMax);
    }

    public void ShowView()
    {
        joinPadView.gameObject.SetActive(true);
    }
    public void HideView()
    {
        joinPadView.gameObject.SetActive(false);
    }
}
